package com.demo.service;

import com.demo.base.AbstractSpringBean;
import com.demo.dao.UserDAO;
import com.demo.domain.UserEntity;
import com.google.common.base.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.triiskelion.tinyspring.dao.TinyPredicate;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: Wang Lei
 * Date: 2015/3/31
 * Time: 19:41
 * <p/>
 * TODO
 */
@Service
public class UserService extends AbstractSpringBean {

    @Resource
    private UserDAO userDAO;

    public boolean login(String username, String password) {
        Optional<UserEntity> optional = userDAO.beginQuery().select().
                where(TinyPredicate.equal("username", username))
                .and(TinyPredicate.equal("password", password))
                .getFirstResult();
        if (optional.isPresent()) {
            return true;
        }
        return false;
    }

    @Transactional
    public boolean register(String username, String password) {
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            UserEntity user = new UserEntity();
            user.setUsername(username);
            user.setPassword(password);
            userDAO.persist(user);
            return true;
        }
        return false;
    }
}
